package com.lj.job.utils;

import com.lj.common.exception.CommonException;
import com.lj.job.entity.ScheduleJob;
import com.lj.job.enums.ScheduleJobStatus;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;

import java.text.ParseException;

/**
 * @author luojing
 * @since 2025/3/20 15:29
 * 定时任务工具类，来源: 人人开源的ScheduleUtils
 */
@Slf4j
public class ScheduleUtils {

    /**
     * 获取触发器key
     */
    public static TriggerKey getTriggerKey(Long jobId) {
        return TriggerKey.triggerKey("TriggerKey_" + jobId);
    }

    /**
     * 获取jobKey
     */
    public static JobKey getJobKey(Long jobId) {
        return JobKey.jobKey("JobKey_" + jobId);
    }

    /**
     * 获取表达式触发器
     */
    public static CronTrigger getCronTrigger(Scheduler scheduler, Long jobId) {
        try {
            return (CronTrigger) scheduler.getTrigger(getTriggerKey(jobId));
        } catch (SchedulerException e) {
            log.warn("获取定时任务CronTrigger出现异常", e);
            throw new CommonException("获取定时任务CronTrigger出现异常");
        }
    }

    /**
     * 获取表达式调度构建器
     *
     * @param cronExpression cron表达式
     */
    public static CronScheduleBuilder getCronScheduleBuilder(String cronExpression) {
        try {
            return CronScheduleBuilder.cronScheduleNonvalidatedExpression(cronExpression)
                    // Misfire机制，错过不再执行任何指令
                    .withMisfireHandlingInstructionDoNothing();
        } catch (ParseException e) {
            throw new CommonException("cron表达式错误: " + cronExpression);
        }
    }

    /**
     * 创建定时任务
     */
    public static void createScheduleJob(Scheduler scheduler, ScheduleJob scheduleJob) {
        try {
            CronScheduleBuilder cronScheduleBuilder = getCronScheduleBuilder(scheduleJob.getCronExpression());
            //构建job信息
            JobDetail jobDetail = JobBuilder
                    .newJob(JobProxy.class)
                    .withIdentity(getJobKey(scheduleJob.getId()))
                    .build();

            //构建trigger
            CronTrigger trigger = TriggerBuilder
                    .newTrigger()
                    .withIdentity(getTriggerKey(scheduleJob.getId()))
                    .withSchedule(cronScheduleBuilder)
                    .build();

            //放入参数，运行时的方法可以获取
            jobDetail.getJobDataMap().put(JobProxy.SCHEDULE_JOB_KEY, scheduleJob);
            // 将任务与触发器进行绑定
            scheduler.scheduleJob(jobDetail, trigger);

            //暂停任务
            if (scheduleJob.getStatus() == ScheduleJobStatus.PAUSE) {
                pauseJob(scheduler, scheduleJob.getId());
            }
        } catch (SchedulerException e) {
            log.warn("创建定时任务失败", e);
            throw new CommonException("创建定时任务失败");
        }
    }

    /**
     * 更新定时任务
     */
    public static void updateScheduleJob(Scheduler scheduler, ScheduleJob scheduleJob) {
        try {
            // 获取旧的触发器
            CronTrigger trigger = getCronTrigger(scheduler, scheduleJob.getId());
            // 获取任务触发器唯一标识
            TriggerKey triggerKey = getTriggerKey(scheduleJob.getId());

            //重新构建trigger
            trigger = trigger.getTriggerBuilder()
                    .withIdentity(triggerKey)
                    .withSchedule(getCronScheduleBuilder(scheduleJob.getCronExpression()))
                    .build();

            //参数
            trigger.getJobDataMap().put(JobProxy.SCHEDULE_JOB_KEY, scheduleJob);
            // 重新设置任务
            scheduler.rescheduleJob(triggerKey, trigger);

            //暂停任务
            if (scheduleJob.getStatus() == ScheduleJobStatus.PAUSE) {
                pauseJob(scheduler, scheduleJob.getId());
            }

        } catch (SchedulerException e) {
            log.warn("更新定时任务失败", e);
            throw new CommonException("更新定时任务失败");
        }
    }

    /**
     * 立即执行任务
     */
    public static void run(Scheduler scheduler, ScheduleJob scheduleJob) {
        try {
            //参数
            JobDataMap dataMap = new JobDataMap();
            dataMap.put(JobProxy.SCHEDULE_JOB_KEY, scheduleJob);

            scheduler.triggerJob(getJobKey(scheduleJob.getId()), dataMap);
        } catch (SchedulerException e) {
            log.warn("立即执行定时任务失败", e);
            throw new CommonException("立即执行定时任务失败");
        }
    }

    /**
     * 暂停任务
     */
    public static void pauseJob(Scheduler scheduler, Long jobId) {
        try {
            scheduler.pauseJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            log.warn("暂停定时任务失败", e);
            throw new CommonException("暂停定时任务失败");
        }
    }

    /**
     * 恢复任务
     */
    public static void resumeJob(Scheduler scheduler, Long jobId) {
        try {
            scheduler.resumeJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            log.warn("暂停定时任务失败", e);
            throw new CommonException("暂停定时任务失败");
        }
    }

    /**
     * 删除定时任务
     */
    public static void deleteScheduleJob(Scheduler scheduler, Long jobId) {
        try {
            scheduler.deleteJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            log.warn("删除定时任务失败", e);
            throw new CommonException("删除定时任务失败");
        }
    }
}